class Solution {
    public int[][] generateMatrix(int n) {
        int start=0;
        int offset = 1;
        int i, j;
        int[][] result = new int[n][n];
        int count = 1;
        int loop=0;

        while (loop++ < n / 2) {
            for (j = start; j < n - offset; j++) {
                result[start][j] = count++;
            }
            for (i = start; i < n - offset; i++) {
                result[i][j] = count++;
            }
            for (; j >= offset; j--) {
                result[i][j] = count++;
            }
            for (; i >= offset; i--) {
                result[i][j] = count++;
            }
            start++;
            offset++;
        }
        if (n % 2 == 1) {
            result[start][start] = count;
        }
        return result;
    }
}
